package com.itlong.cloud.controller.operate;

import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.equip.operate.IOperateTokenImportServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <desc>
 *      运营-运营管理模块-硬件token账号导入
 * </desc>
 *
 * @createDate 2018/07/16
 */
@RestController
@RequestMapping("/marketer/tokenImport")
public class OperateTokenImportController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(OperateTokenImportController.class);

    @Autowired
    private IOperateTokenImportServiceClient iOperateTokenImportServiceClient;  // 导入云对讲第三方账号token服务接口暴露对象

    /**
     * <desc>
     *      第三方提供云对讲token账号导入接口
     * </desc>
     *
     * @param request HTTP协议对象
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/07/16
     */
//    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.CLOUD_INTERCOM_TOKEN_IMPORT_LOG_DESC)
    @ResponseBody
    @PostMapping(path = "import")
    public Object importCloudIntercomToken(HttpServletRequest request){
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile("file");
            if (file == null || file.isEmpty()){
                LOG.info("【云对讲token账号导入接口】没有选择上传的文件");
                return new MessageVO(OperateErrorCodeEnum.CLOUD_INTERCOM_FILE_EMPTY_ERR.getErrorCode());
            }
            Map<String,String> accountAndToken = new LinkedHashMap<>();
            String readString;
            InputStream inputStream = null;
            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;
            try {
                // 获取该文本文件的输入流
                inputStream = file.getInputStream();
                // 编码选择utf-8
                inputStreamReader = new InputStreamReader(inputStream,"utf-8");
                // 获取缓冲读取流对象
                bufferedReader = new BufferedReader(inputStreamReader);
                // 不在迭代条件中加readString为空字符串的情况，否则不会继续迭代，而无法规避行与行之间存在空行的情况
                while ((readString = bufferedReader.readLine()) != null) {
                    // 规避行与行之间存在空行的情况
                    if (StringUtils.isBlank(readString)) {
                        continue;
                    }
                    String[] strings = readString.split(" ");
                    // 规避一行中两个字符串中间存在多个空格的情况，同时规避一行中只有一个字符串的情况
                    if (StringHandlerUtil.compareStrWithOutEmpty(strings[0], strings[strings.length - 1])) {
                        return new MessageVO(OperateErrorCodeEnum.CLOUD_INTERCOM_FILE_FORMAT_ERR.getErrorCode());
                    }
                    accountAndToken.put(strings[0], strings[strings.length - 1]);
                }
                if (accountAndToken.isEmpty()){
                    //LOG.info("【云对讲token账号导入接口】上传的文件中无可用数据");
                    return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                //LOG.info("【云对讲token账号导入接口】解析得到所有账号数据");
                iOperateTokenImportServiceClient.importCloudIntercomToken(accountAndToken);
            }catch (IOException e) {
                throw new DataAccessException("【运营_运营管理模块_导入云对讲token账号】导入云对讲token账号失败", e);
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                    }
                }
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) {
                    }
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e) {
            throw new DataAccessException("【运营_运营管理模块_导入云对讲token账号】导入云对讲token和账号失败", e);
        }
    }

    /**
     * <desc>
     *      第三方提供云对讲appid应用账号导入接口
     * </desc>
     *
     * @param request HTTP协议对象
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2018/12/19
     */
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.CLOUD_INTERCOM_THIRD_APPID_IMPORT_LOG_DESC)
    @PostMapping(path = "importAppid")
    public Object importCloudIntercomAppid(HttpServletRequest request){
        try {
            //LOG.info("【云对讲appid应用账号导入接口】接收到请求");
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile("file");
            if (file == null || file.isEmpty()){
                LOG.info("【云对讲appid应用账号导入接口】没有选择上传的文件");
                return new MessageVO(OperateErrorCodeEnum.CLOUD_INTERCOM_APPID_FILE_EMPTY_ERR.getErrorCode());
            }
            Map<String,String> appid = new LinkedHashMap<>();
            String readString;
            InputStream inputStream = null;
            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;
            try {
                // 获取该文本文件的输入流
                inputStream = file.getInputStream();
                // 编码选择utf-8
                inputStreamReader = new InputStreamReader(inputStream,"utf-8");
                // 获取缓冲读取流对象
                bufferedReader = new BufferedReader(inputStreamReader);
                // 不在迭代条件中加readString为空字符串的情况，否则不会继续迭代，而无法规避行与行之间存在空行的情况
                while ((readString = bufferedReader.readLine()) != null) {
                    // 规避行与行之间存在空行的情况
                    if (StringUtils.isBlank(readString)) {
                        continue;
                    }
                    String[] strings = readString.split(" ");
                    // 规避一行中两个字符串中间存在多个空格的情况，同时规避一行中只有一个字符串的情况
                    if (StringHandlerUtil.compareStrWithOutEmpty(strings[0], strings[strings.length - 1])) {
                        return new MessageVO(OperateErrorCodeEnum.CLOUD_INTERCOM_APPID_FILE_FORMAT_ERR.getErrorCode());
                    }
                    appid.put(strings[0], strings[strings.length - 1]);
                }
                if (appid.isEmpty()){
                    LOG.info("【云对讲appid应用账号导入接口】上传的文件中无可用数据");
                    return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                //LOG.info("【云对讲appid应用账号导入接口】解析得到所有账号数据");
                iOperateTokenImportServiceClient.importCloudIntercomAppid(appid);
            }catch (IOException e) {
                throw new DataAccessException("【运营_运营管理模块_导入云对讲appid应用账号】导入云对讲appid应用账号失败", e);
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                    }
                }
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) {
                    }
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e) {
            throw new DataAccessException("【运营_运营管理模块_导入云对讲appid应用账号】导入云对讲appid应用和账号失败", e);
        }
    }

}
